package com.asj.service.binding;

import static android.content.ContentValues.TAG;

import static com.asj.enums.AppIdentifierDictEnums.not_lasted_op;
import static com.asj.enums.ControlProgressBarEnum.already_bind_step;
import static com.asj.enums.ControlProgressBarEnum.already_setting_app_install_listener;
import static com.asj.enums.ControlProgressBarEnum.already_setting_network_listener;
import static com.asj.enums.ControlProgressBarEnum.bind_step;
import static com.asj.enums.ControlProgressBarEnum.cancel_all_restrict;
import static com.asj.enums.ControlProgressBarEnum.check_device_status;
import static com.asj.enums.ControlProgressBarEnum.check_device_status_success;
import static com.asj.enums.ControlProgressBarEnum.connection_success;
import static com.asj.enums.ControlProgressBarEnum.device_is_binding;
import static com.asj.enums.ControlProgressBarEnum.restrict_success;
import static com.asj.enums.ControlProgressBarEnum.setting_insurance_success;
import static com.asj.enums.ControlProgressBarEnum.start_binding_device;
import static com.asj.enums.ControlProgressBarEnum.start_connection;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_UN_EXIST;
import static com.asj.enums.DeviceIdentifierDictEnums.PENDING_SUPERVISE;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_code;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_deviceCode;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_message;
import static com.asj.enums.AppIdentifierDictEnums.supervision_NotSave;
import static com.asj.enums.AppIdentifierDictEnums.supervision_cancel;
import static com.asj.enums.AppIdentifierDictEnums.supervision_initiate;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_result;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_superviseStatus;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.asj.MainActivity;
import com.asj.MainActivityService;
import com.asj.enums.ControlProgressBarEnum;
import com.asj.enums.DeviceIdentifierDictEnums;
import com.asj.receiver.AppInstallReceiver;
import com.asj.service.StayAliveService;
import com.asj.service.WarehouseService;
import com.asj.service.recover.RecoverDeviceInfoService;
import com.asj.service.recover.correct.CorrectDeviceAppInfo;
import com.asj.service.request.RequestMDMService;
import com.asj.service.control.ControlProgressBarService;
import com.asj.service.oppoSdk.OPPOControlService;
import com.asj.service.oppoSdk.OPPOSDKService;
import com.asj.utils.CommonsUtils;
import com.asj.utils.ResultUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * 绑定服务之一：判断设备服务
 * */
public class BindingAffirmDeviceService extends WarehouseService {

    /**
     * 判断设备存在的方法
     * */
    public static void affirmDeviceBind(MainActivity mainActivity){
        try {
            OPPOSDKService instance = new OPPOSDKService(mainActivity);
            /* 1.获取设备码 */
            String deviceCode = instance.getIMEI();

            /* 2.设立异步方法，查询数据(不使用异步会报错，android不允许在Activity的线程中去处理网络请求) */
            new Thread(() -> {
                /* 3.检查设备是否在后台存在的方法 */
                JsonObject deviceInfo = checkExistRetry(deviceCode);
                //确认结果是否为true
                if(ResultUtils.isOK(deviceInfo.get(json_key_code.getValue()).getAsString())){
                    JsonElement jsonElement = deviceInfo.get(json_key_result.getValue());
                    if(jsonElement.isJsonObject()){
                        //获取监管状态
                        JsonObject result = deviceInfo.get(json_key_result.getValue()).getAsJsonObject();
                        //如果设备是待解除监管状态，则不需要走下面的检测绑定流程
                        if(result != null && !result.isJsonNull()){
                            JsonElement superviseStatus = result.get(json_key_superviseStatus.getValue());
                            if(superviseStatus != null && superviseStatus.getAsString().equals(PENDING_SUPERVISE.getValue())){
                                Log.w("检测绑定流程：","设备处于待取消监管状态，不执行检测绑定流程，执行状态矫正流程"); /* 2.修正设备状态 */
                                JsonObject taskFlowData = new JsonObject();
                                //获取当前设备的imei
                                OPPOSDKService opposdkService = new OPPOSDKService(mainActivity);
                                taskFlowData.addProperty(json_key_deviceCode.getValue(),CommonsUtils.getDeviceCode(opposdkService.getIMEI()));
                                RecoverDeviceInfoService.correctDeviceStatusInfo(taskFlowData,null,mainActivity);
                                mainActivity.finishAffinity();
                                return;
                            }
                        }
                    }
                    /* 4.初始化进度组件，用于展示绑定步骤 */
                    ControlProgressBarService.setProgressBar(mainActivity);
                    ControlProgressBarService.setRecyclerView(mainActivity);
                    //默认长度为绑定的长度，13步
                    ControlProgressBarService.initProgressBarValue(bind_step.getValue(),0,mainActivity);

                    ControlProgressBarEnum.setValueAndMessage(start_connection);

                    Log.w("检测绑定流程：","开始执行检测绑定流程");
                    ControlProgressBarEnum.setValueAndMessage(connection_success);

                    OPPOControlService oppoControlService = new OPPOControlService(mainActivity);
                    String message = deviceInfo.get(json_key_message.getValue()).getAsString();

                    /* 4.1 设备完全不存在，不允许进入绑定流程*/
                    if(DEVICE_UN_EXIST.getValue().equals(message)){
                        ControlProgressBarService.setProgressBarAndListValue(bind_step.getValue(), DEVICE_UN_EXIST.getRemark());
                    }
                    /* 4.2 设备允许进入绑定流程 */
                    else if(DeviceIdentifierDictEnums.deviceUnExistButCanBind.getValue().equals(message)){
                        /* 4.2.1 取消设备的监管，作为一层保险，为了保证重新上锁 */
                        oppoControlService.initiateOrCancelSupervision(supervision_NotSave.getValue(), supervision_cancel.getValue());
                        ControlProgressBarEnum.setValueAndMessage(cancel_all_restrict);

                        /* 4.2.2，防止绑定过程中间退出出现问题，锁定屏幕 */
                        oppoControlService.lockMachine(null,null,null);
                        ControlProgressBarEnum.setValueAndMessage(start_binding_device);

                        /* 4.2.3 开始执行存储设备信息的流程 */
                        BindingSaveDeviceService.saveDevice(mainActivity);
                    }
                    /* 4.3 设备存在则进行检查各项监管项 */
                    else{
                        //重新设置进度条为已绑定的长度
                        ControlProgressBarService.setProgressBarMax(already_bind_step.getValue(),mainActivity);
                        //添加deviceCode在其中，方便后面矫正环节
                        try {
                            ControlProgressBarEnum.setValueAndMessage(device_is_binding);
                            /* 4.3.1 启动监管项，但是需要说明不是绑定流程中启动的 */
                            oppoControlService.initiateOrCancelSupervision(supervision_NotSave.getValue(),supervision_initiate.getValue());

                            ControlProgressBarEnum.setValueAndMessage(restrict_success);

                            /* 4.3.2 开始检测设备与后台是否出现了信息差距 */
                            settingRestrictAfter(deviceInfo,mainActivity,oppoControlService);
                        } catch (IntentFilter.MalformedMimeTypeException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }else{
                    AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
                    builder.setCancelable(false);
                    builder.setTitle("提示！");
                    builder.setMessage(deviceInfo.get("message").getAsString());
                    builder.setPositiveButton("知道了", (dialog, which) -> {
                        // 关闭所有活动并退出应用
                        mainActivity.finishAffinity();
                        System.exit(0);
                    });
                    mainActivity.runOnUiThread(()->{
                        builder.create().show();
                    });
                }
            }).start();
        }catch (Exception e){
            System.out.println("异常信息："+e.getMessage());
        }
    }



    /**
     * 查询设备是否存在，并返回结果，如果出现意外无法进行建立请求，则进行重试
     * */
    public static JsonObject checkExistRetry(String deviceCode){
        //设备存在结果
        JsonObject deviceExitsResult = null;
        /* 1.设立计数器，最大重试次数，是否成功获取数据的标记 */
        int retryCount = 0; // 重试计数器
        final int maxRetries = 15; // 最大重试次数
        boolean success = false; // 标记是否成功获取bind值


        /* 2.设立循环，重复请求，除非请求成功 或 直到最大重试次数停止 */
        while (!success && retryCount < maxRetries) {
            try {
                deviceExitsResult = RequestMDMService.queryExistDevice(deviceCode);
                if(deviceExitsResult != null){
                    success = true; // 假设一旦成功获取返回值，就不再重试
                }else{
                    retryCount++; // 增加重试计数
                    // 可以选择在这里添加延时，避免立即重试
                    try {
                        Thread.sleep(2500);//2.5秒后重试
                        ControlProgressBarService.setProgressBarAndListValue(retryCount,"检查绑定时发生错误，正在尝试第"+ retryCount +"次重试");
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            } catch (Exception e) {
                // 处理异常，例如打印日志
                Log.e(TAG, "检查绑定时发生错误！" + e.getMessage());
            }
        }

        /* 3.到最后也没有请求成功，则放出提示 */
        if (!success) {
            ControlProgressBarService.setProgressBarAndListValue(maxRetries,"已达到最大重试次数，请检查网络是否连接，如若不行请联系运营商");
        }
        return deviceExitsResult;
    }

    /**
     * 设置监管后
     * */
    public static void settingRestrictAfter(JsonObject deviceInfo,
                                            MainActivity mainActivity,
                                            OPPOControlService oppoControlService) throws IntentFilter.MalformedMimeTypeException {
        try {
            /* 1.矫正设备的状态，确保不是异常 */
            ControlProgressBarEnum.setValueAndMessage(check_device_status);
            RecoverDeviceInfoService.correctDeviceStatusInfo(deviceInfo,mainActivity,null);

            ControlProgressBarEnum.setValueAndMessage(check_device_status_success);
            //启动后台常驻服务
            MainActivityService.startService(mainActivity);

            //发布通知告诉设备正常
            CommonsUtils.showNotification(mainActivity,"设备已绑定","设备监管状态正常");
        }catch (Exception e){
            AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
            builder.setCancelable(false);
            builder.setTitle("设备监管出错！");
            builder.setMessage("请退出程序并联系开发人员！"+e.getMessage());
            builder.setPositiveButton("知道了", (dialog, which) -> {
                // 关闭所有活动并退出应用
                mainActivity.finishAffinity();
                System.exit(0);
            });
            mainActivity.runOnUiThread(()->{
                builder.create().show();
            });
            //未绑定设备，解除监管
            oppoControlService.initiateOrCancelSupervision(supervision_NotSave.getValue(),supervision_cancel.getValue());
            //解除锁定
            oppoControlService.unlockMachine(false);
        }
    }


}

